package krao.parser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;

import krao.data.ABox;
import krao.data.Atom;
import krao.data.ClassAtom;
import krao.data.RoleAtom;

public class ABoxParser extends AtomParser {
	public static ABox getABox(String aboxFilePath) {
		return parseABoxFromFile(aboxFilePath);
	}

	private static ABox parseABoxFromFile(final String fileName) {
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(fileName));
		} catch (FileNotFoundException e1) {
			logger.error("File " + fileName + " could not be found.");
			return null;
		}

		ABox abox = new ABox();
		String line;
		try {
			while ((line = br.readLine()) != null) {
				if (!line.startsWith("#") && !line.equals("")) {
					abox.addAssertion(parseAboxAtom(line));
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return abox;
	}

	private static Atom parseAboxAtom(String atomText) {
		atomText = atomText.replaceAll("\\s", "");
		if (!atomPattern.matcher(atomText).matches()) {
			logger.error("Invalid atom supplied (skipped): " + atomText);
			return null;
		}

		Matcher roleMatcher = rolePattern.matcher(atomText);
		if (roleMatcher.matches()) {
			RoleAtom ra = new RoleAtom(roleMatcher.group(1), roleMatcher.group(2),
					roleMatcher.group(3));
			logger.debug(ra);
			return ra;
		} else {
			Matcher classMatcher = classPattern.matcher(atomText);
			if (classMatcher.matches()) {
				ClassAtom ca = new ClassAtom(classMatcher.group(1), classMatcher.group(2));
				logger.debug(ca);
				return ca;
			}
		}
		return null;
	}
}
